# app.py - Flask主服务
from flask import Flask, render_template, jsonify
import sqlite3
import time
import threading
from sklearn.cluster import KMeans
import numpy as np
import pandas as pd

app = Flask(__name__)

# 数据库配置
def init_db():
    conn = sqlite3.connect('electric_meter.db')
    cursor = conn.cursor()
    cursor.execute('''
    CREATE TABLE IF NOT EXISTS electricity_data (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        timestamp TEXT,
        voltage REAL,
        current REAL,
        power REAL,
        energy REAL
    )
    ''')
    conn.commit()
    conn.close()

# AI用电模式分析模块
class EnergyPatternAnalyzer:
    def __init__(self):
        self.model = KMeans(n_clusters=3)
        self.is_trained = False
        self.data_history = []
        
    def add_data(self, data):
        timestamp = pd.to_datetime(data['timestamp'])
        hour = timestamp.hour
        self.data_history.append([hour, data['power'], data['voltage']])
        
        # 当有足够数据时训练模型
        if len(self.data_history) >= 500 and not self.is_trained:
            self.model.fit(self.data_history)
            self.is_trained = True
            
    def analyze_pattern(self, data):
        if not self.is_trained:
            return {"status": "normal", "suggestion": "数据不足，无法分析"}
        
        timestamp = pd.to_datetime(data['timestamp'])
        hour = timestamp.hour
        sample = np.array([[hour, data['power'], data['voltage']]])
        cluster = self.model.predict(sample)[0]
        
        # 根据聚类结果生成建议
        if cluster == 0:
            return {"status": "normal", "suggestion": "当前用电模式正常"}
        elif cluster == 1:
            return {"status": "high", "suggestion": "当前用电偏高，建议关闭不必要的电器"}
        else:
            return {"status": "anomaly", "suggestion": "检测到异常用电模式，请检查电路"}

# 创建能源分析器实例
energy_analyzer = EnergyPatternAnalyzer()

# 模拟数据采集函数（实际应用中应从串口读取）
def mock_data_collection():
    # 生成模拟数据进行演示
    import random
    while True:
        try:
            # 模拟电压、电流和功率数据
            current_hour = time.localtime().tm_hour
            
            # 模拟不同时间段的用电模式
            if 0 <= current_hour < 6:
                # 夜间低用电模式
                voltage = 220.0 + random.uniform(-5, 5)
                current = 0.5 + random.uniform(0, 0.5)
            elif 6 <= current_hour < 12:
                # 早晨中等用电模式
                voltage = 220.0 + random.uniform(-5, 5)
                current = 1.0 + random.uniform(0, 1.0)
            elif 12 <= current_hour < 18:
                # 中午中等用电模式
                voltage = 220.0 + random.uniform(-5, 5)
                current = 0.8 + random.uniform(0, 0.8)
            else:
                # 晚上高用电模式
                voltage = 220.0 + random.uniform(-5, 5)
                current = 1.5 + random.uniform(0, 1.5)
            
            # 计算功率和用电量
            power = voltage * current
            energy = power / 3600.0  # 转换为kWh
            
            # 添加时间戳
            timestamp = time.strftime('%Y-%m-%d %H:%M:%S')
            data = {
                'timestamp': timestamp,
                'voltage': voltage,
                'current': current,
                'power': power,
                'energy': energy
            }
            
            # 存储到数据库
            conn = sqlite3.connect('electric_meter.db')
            cursor = conn.cursor()
            cursor.execute(
                "INSERT INTO electricity_data (timestamp, voltage, current, power, energy) VALUES (?, ?, ?, ?, ?)",
                (timestamp, data['voltage'], data['current'], data['power'], data['energy'])
            )
            conn.commit()
            conn.close()
            
            # AI用电模式分析
            energy_analyzer.add_data(data)
            
            # 每5秒采集一次数据（模拟）
            time.sleep(5)
            
        except Exception as e:
            print(f"错误: {e}")
            time.sleep(1)

# 启动数据采集线程
threading.Thread(target=mock_data_collection, daemon=True).start()

# Web路由
@app.route('/')
def index():
    return render_template('index.html')

@app.route('/api/data')
def get_data():
    conn = sqlite3.connect('electric_meter.db')
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM electricity_data ORDER BY timestamp DESC LIMIT 100")
    rows = cursor.fetchall()
    conn.close()
    
    data = []
    for row in rows:
        data.append({
            'timestamp': row[1],
            'voltage': row[2],
            'current': row[3],
            'power': row[4],
            'energy': row[5]
        })
    
    return jsonify(data)

@app.route('/api/latest')
def get_latest_data():
    conn = sqlite3.connect('electric_meter.db')
    cursor = conn.cursor()
    cursor.execute("SELECT * FROM electricity_data ORDER BY timestamp DESC LIMIT 1")
    row = cursor.fetchone()
    conn.close()
    
    if row:
        data = {
            'timestamp': row[1],
            'voltage': row[2],
            'current': row[3],
            'power': row[4],
            'energy': row[5]
        }
        
        # 获取AI分析结果
        if energy_analyzer.is_trained:
            analysis = energy_analyzer.analyze_pattern(data)
            data['analysis'] = analysis
        
        return jsonify(data)
    else:
        return jsonify({})

@app.route('/api/report')
def generate_report():
    # 生成日用电报告
    conn = sqlite3.connect('electric_meter.db')
    cursor = conn.cursor()
    
    # 获取今天的数据
    today = time.strftime('%Y-%m-%d')
    cursor.execute("SELECT * FROM electricity_data WHERE timestamp LIKE ?", (today + '%',))
    rows = cursor.fetchall()
    conn.close()
    
    if rows:
        total_energy = sum(row[5] for row in rows)
        max_power = max(row[4] for row in rows)
        avg_voltage = sum(row[2] for row in rows) / len(rows)
        
        return jsonify({
            'date': today,
            'total_energy': total_energy,
            'max_power': max_power,
            'avg_voltage': avg_voltage,
            'record_count': len(rows)
        })
    else:
        return jsonify({'error': '今日无数据'})

if __name__ == '__main__':
    # 初始化数据库
    init_db()
    app.run(debug=True, host='0.0.0.0')